import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue';
import Read from '../views/Read.vue'
import Writing from '../views/Writing.vue'
import ReadPage from '../views/ReadPage.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import AdminList from '../views/AdminList.vue'

Vue.use(VueRouter)

const routes = [
  //meta:{idPublic:true}表示允许公开访问，在下边路由守卫做处理
  { path: '/login', name: 'Login', component: Login, meta: { isPublic: true } },
  {
    path: '/',
    name: 'Home',
    component: Home,
    children: [
      { path: '/read', name: 'Read', component: Read },
      { path: '/writing', name: 'Writing', component: Writing },
      { path: '/writing/:id', name: 'WritingChange', component: Writing, props: true },
      { path: '/readpage/:id', name: 'ReadPage', component: ReadPage, props: true },
    ],
    redirect: '/read'  //默认展示的二级路由
  },
  { path: '/register', name: 'Register', component: Register },
  { path: '/adminlist', name: 'AdminList', component: AdminList },
]

const router = new VueRouter({
  routes
})

//路由前置守卫（后端利用token验证可以阻止查看列表那一半页面，编辑页需要在前端进行路由守卫）
router.beforeEach((to, from, next) => { 
  if (!to.meta.isPublic && !localStorage.token) {
    return next('/login')
  }
  next()
})

export default router
